/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package servlet;

import DTO.user.Users;
import DTO.user.Users.User;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;

/**
 *
 * @author TungNT60513
 */
public class AjaxLoginServlet extends HttpServlet {

    private final String xmlPath = "xml/Users.xml";
    private User foundUser = null;
    private Users listUsers = null;

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        InputStream is = null;
        XMLStreamReader xsr = null;

        try {
            String realPath = getServletContext().getRealPath("/");
            String filePath = realPath + xmlPath;

            String userName = request.getParameter("txtUsername");
            String password = request.getParameter("txtPassword");

            XMLInputFactory xif = XMLInputFactory.newInstance();
            File file = new File(filePath);
            is = new FileInputStream(file);
            xsr = xif.createXMLStreamReader(is);

            Boolean found = false;
            while (xsr.hasNext()) {
                int event = xsr.next();
                if (event == XMLStreamConstants.START_ELEMENT) {
                    String elementName = xsr.getLocalName();
                    if (elementName.equals("Username")) {
                        xsr.next();//Username value
                        String user = xsr.getText().trim();
                        if (userName.equals(user)) {
                            xsr.nextTag();//end Username
                            xsr.nextTag();//Password
                            xsr.next();//Password value
                            String pass = xsr.getText().trim();
                            if (password.equals(pass)) {
                                // Lay du lieu thong tin cua user tu file xml
                                foundUser = new User();
                                foundUser.setUsername(user);
                                foundUser.setPassword(pass);
                                xsr.nextTag();//end Password
                                xsr.nextTag();//Email
                                xsr.next();//Email value
                                foundUser.setEmail(xsr.getText().trim());
                                xsr.nextTag();//end Email
                                xsr.nextTag();//isAdmin
                                xsr.next();//isAdmin value
                                foundUser.setIsAdmin(Boolean.valueOf(xsr.getText().trim()));
                                listUsers = new Users();
                                listUsers.getUser().add(foundUser);

                                found = true;
                                break;
                            }//end password
                        }
                    }//end username
                }//end start element
            }//end while
            if (found) {
                HttpSession session = request.getSession(true);
                session.setAttribute("USER", userName.trim());
                

                JAXBContext ctx = JAXBContext.newInstance(listUsers.getClass());
                Marshaller mar = ctx.createMarshaller();
                mar.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
                mar.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

                response.setContentType("text/xml");
                response.setCharacterEncoding("UTF-8");
                mar.marshal(listUsers, out);

            }
        } catch (XMLStreamException ex) {
            Logger.getLogger(AjaxLoginServlet.class.getName()).log(Level.SEVERE, null, ex);
        } catch (JAXBException ex) {
            Logger.getLogger(AjaxLoginServlet.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
